package com.ce.pms.house.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.hibernate.Query;
import org.hibernate.SQLQuery;

import com.ce.pms.base.dao.impl.PmsBaseDaoImpl;
import com.ce.pms.common.model.SysrefcodeDO;
import com.ce.pms.exception.BusinessException;
import com.ce.pms.house.dao.IGoodsRecordDao;
import com.ce.pms.house.model.GoodsRecordDomain;

public class GoodsRecordDaoImpl extends PmsBaseDaoImpl<GoodsRecordDomain> implements IGoodsRecordDao{

	public boolean isUsed(GoodsRecordDomain good) {
		StringBuffer sql = new StringBuffer("SELECT * FROM HM_GO_OUT_R_GOODS_RECORD WHERE HM_GO_OUT_R_GOODS_RECORD.GOODS_RECORD_ID = ?");

		SQLQuery query = (SQLQuery) super.createSQLQuery(sql.toString(), new Object[]{good.getKeyword()});

		return (query.list().size() > 0)?true:false;
	}

	public boolean nameAlreadyExist(GoodsRecordDomain good) {
		StringBuffer sql = new StringBuffer("SELECT * FROM HM_GOODS_RECORD WHERE HM_GOODS_RECORD.NAME = ? ");
		List<Object> parameter = new ArrayList<Object>();
		parameter.add(good.getName());

		//如果是查询出来的则不比较自身
		if (good.getKeyword() != null ) {
			sql.append(" AND HM_GOODS_RECORD.GOODS_RECORD_ID <> ? ");
			parameter.add(good.getKeyword());
		}

		SQLQuery query = (SQLQuery) super.createSQLQuery(sql.toString(), parameter.toArray());

		return (query.list().size() > 0)?true:false;
	}

	public List<GoodsRecordDomain> findGoodsRecordsByIds(String goodIds){

		if (!Pattern.matches(SysrefcodeDO.REGEX_ID_JOIN_STRING, goodIds)) {
			throw new BusinessException("common:id_join_string_format_exception",BusinessException.WARNING);
		}
		String queryStr = "FROM BuildingDomain bd WHERE bd.id IN (:idString) ";
		queryStr=queryStr.replace(":idString", goodIds);
		Query query=this.createQuery(queryStr);

		return query.list();
	}

	public List<GoodsRecordDomain> getAllGoodsRecords(){
		String queryStr = "SELECT * FROM `HM_GOODS_RECORD` hgr ORDER BY IF(hgr.`SEQ_NO` is NULL,(SELECT max(hgr1.`SEQ_NO`) FROM `HM_GOODS_RECORD` hgr1)+1,hgr.`SEQ_NO`);";

		Query query=this.createSQLQuery(queryStr);
		List<Object[]> listObj = query.list();
		List<GoodsRecordDomain> list = new ArrayList<GoodsRecordDomain>();
		for(Object[] objects : listObj){
			GoodsRecordDomain goodsRecordDomain = new GoodsRecordDomain();
			goodsRecordDomain.setKeyword(new Long(objects[0].toString()));
			goodsRecordDomain.setName(objects[1].toString());
			goodsRecordDomain.setSeqNo((Short) objects[3]);
			list.add(goodsRecordDomain);
		}
		return list;
	}

}
